import React, { useEffect, useRef, useState } from 'react';
import ReactMarkdown from 'react-markdown';
import rehypeRaw from 'rehype-raw';
import remarkMath from 'remark-math';
import remarkGfm from 'remark-gfm';
import remarkBreaks from 'remark-breaks';
import rehypeKatex from 'rehype-katex';
import CodeBlock from './CodeBlock';
import Reference from './Reference';
import CustomControl from './CustomControl';
import mdStyles from '../styles/markdown.module.scss';

import styles from '../styles/Reference.module.css';

import { SvgIcon } from '@/components/icon';

import { Tooltip, Rate, message, Tag } from 'antd';
import appService from '@/api/services/appService';
import { useParams } from '@/router/hooks';
import { useDebounceFn, useInViewport, useSize } from 'ahooks';
import { ChatItem } from '@/types/chat';
import { useIsDeepMode } from '@/store/chatStore';

import ThoughtChainALL from './thoughtChainALL';
import { ThoughtChainItem } from '@ant-design/x';

import {
  removeRefTags,
  fixUrlPunctuation,
  convertImageNames,
} from '@/utils/regexRules';

import { useConfig } from '@/store/configStore';

import { useBrowserCompatibility } from '@/hooks/event/use-browser-compatibility';

import GuessYouWantToAsk from './GuessYouWantToAsk';

interface ChatProps {
  item: ChatItem;
  index: number;
  hideItem?: boolean;
  isLastOne?: boolean;
  deleteMessage?: (index: number) => void;
  reFreshAnswer?: (index: number) => void;
  scrollToBottom?: () => void;
  handleSend: (message: string) => void;
  isMessageSend?: boolean;
  guessQuestions?: { id: string; content: string }[];
  onQuestionClick?: (question: string) => void;
}

const MessageItem = ({
  item,
  index,
  hideItem,
  isLastOne,
  deleteMessage,
  reFreshAnswer,
  handleSend,
  scrollToBottom,
  isMessageSend,
  guessQuestions,
  onQuestionClick,
}: ChatProps) => {
  const { title } = useConfig();
  const [isExpanded, setIsExpanded] = useState(false);
  const ref = useRef(null);
  const [inViewport] = useInViewport(ref);
  const [isShow, setIsShow] = useState(true);
  const size = useSize(ref);
  const isDeepMode = useIsDeepMode();
  const [keyArr, setKeyArr] = useState([]);
  const { isSupported } = useBrowserCompatibility();

  const replaceNewlinesWithBr = (str: string) => {
    return str.trim().replace(/\n/g, '<br>');
  };

  const preprocessMarkdown = (text: string): string => {
    let processedText = text;

    try {
      processedText = removeRefTags(processedText);
      // processedText = addTableHeader(processedText);
      processedText = fixUrlPunctuation(processedText);
      processedText = convertImageNames(processedText);
    } catch (error) {
      console.error('Error during markdown preprocessing:', error);
    }

    return processedText;
  };

  const [thoughtListAll, setThoughtListAll] = useState<ThoughtChainItem>([]);

  const removeThinkTags = (text) => {
    // 使用正则表达式匹配<think>标签及其内容，并将其替换为空字符串
    return text.replace(/<think>.*?<\/think>/gs, '');
  };

  const extractThinkContents = (text) => {
    const regex = /<think>(.*?)<\/think>/gs;
    let matches;
    const thinkContents = [];

    while ((matches = regex.exec(text)) !== null) {
      thinkContents.push(matches[1]); // 将捕获组的内容（标签内的文本）添加到数组中
    }

    return thinkContents;
  };

  const extractThinkContents1 = (text) => {
    const regex = /<think>\s*([\s\S]*)/gs;
    let matches;
    const thinkContents = [];

    while ((matches = regex.exec(text)) !== null) {
      thinkContents.push(matches[1]); // 将捕获组的内容（标签内的文本）添加到数组中
    }

    return thinkContents;
  };

  const isThinking = () => {
    if (item.text?.trimStart()?.startsWith('<think') && !item.text?.includes('</think>')) {
      return true;
    } else {
      return false;
    }
  };

  useEffect(() => {
    const isThink = isThinking();

    if (item.text) {
      const extractedContents = isThink
        ? extractThinkContents1(item.text)
        : extractThinkContents(item.text);
      const Arr = [];
      if (item.thinkList && item.thinkList.length > 0) {
        setKeyArr(['1', '2'])
        const thinkNodes = Array.from(item.thinkList ?? []);
        if (isDeepMode) {

          if ((item.text.length > 10 || item.text.startsWith('\n<think>')) && thinkNodes.length > 0 && !isThinking()) {
            const thoughtItem = {
              title: '组织答案',
              description: '暂无',
              status: 'success',
              id: 'sdfadfadsf',
              // icon: getStatusIcon('success'),
            };
            thinkNodes.push(thoughtItem);
          }
        } else {
          if (item.text.length > 1 && thinkNodes.length > 0 && !isThinking()) {
            const thoughtItem = {
              title: '组织答案',
              description: '暂无',
              status: 'success',
              // icon: getStatusIcon('success'),
            };
            thinkNodes.push(thoughtItem);
          }
        }

        Arr.push({
          label: (
            <div className="flex items-center">
              {/* {isMessageSend && isLastOne ? <LoadingOutlined /> : <CheckOutlined />} */}
              {isMessageSend && isLastOne ? (
                <SvgIcon icon='eos-icons--installing' size={20} color='#8890ff'></SvgIcon>
              ) : (
                <SvgIcon icon='eos-icons--static' size={15} color='#8890ff'></SvgIcon>
              )}

              <span className="ml-3">{'工作流执行'}</span>
            </div>
          ),
          // description: 'Collapsible',
          // content: <ThoughtChain thoughtList={item.thinkList}></ThoughtChain>,
          children: (
            <div className="flex flex-wrap gap-2">
              {thinkNodes?.map((thinkItem, thinkIndex) => {
                return (
                  <span className="flex items-center" key={thinkItem.title}>
                    <Tag
                      color="#eaebff"
                      key={thinkItem.title}
                      bordered={false}
                      style={{ fontSize: '14px', color: '#6273a8', height: '26px', lineHeight: '26px' }}
                    // style={{ marginBottom: '4px' }}
                    // closeIcon={<SwapRightOutlined />}
                    // onClose={() => {}}
                    >
                      {thinkItem.title}
                    </Tag>
                    {thinkNodes?.length - 1 === thinkIndex ? (
                      <React.Fragment>
                        {isMessageSend && isLastOne ? (
                          // <img className="h-5 w-5" src={think_load2} alt="" />
                          // <LoadingOutlined/>
                          <SvgIcon icon='line-md--loading-alt-loop' size={20} color='#8890ff'></SvgIcon>
                        ) : (
                          ''
                        )}
                      </React.Fragment>
                    ) : (
                      // <SwapRightOutlined />
                      <SvgIcon icon='line-md--arrow-small-right' size={20} color='#8890ff'></SvgIcon>
                      // <img className="h-5 w-5" src={toright} alt="" />
                    )}
                  </span>
                );
              })}
            </div>
          ),
          key: '1',
        });
      }

      if (extractedContents.length > 0) {
        Arr.push({
          label: (
            <div>
              {(isMessageSend && isThink) ? (
                <div className="flex items-center">
                  <SvgIcon icon='rj-dot-rotate' size={20} color='#8890ff'></SvgIcon>
                  <span className="ml-3">{'问题思考中...'}</span>
                </div >
              ) : (
                <div className="flex items-center">
                  <SvgIcon icon='rj-dot-static' size={20} color='#8890ff'></SvgIcon>
                  <span className="ml-3">{'问题思考'}</span>
                </div>
              )}
            </div >
          ),
          // description: 'Collapsible',
          children: (
            <div className="flex w-full">
              <div
                style={{ borderLeft: '1px solid #8080809e', paddingLeft: '10px', color: 'gray' }}
              ></div>

              {/* <div style={{ color: 'gray' }} dangerouslySetInnerHTML={{ __html: extractedContents[0] }} > */}
              {/* <div style={{ color: 'gray' }}>
                {extractedContents[0]}
              </div> */}
              <div
                style={{
                  width: '100%',
                  color: 'gray',
                  wordWrap: 'break-word',
                  whiteSpace: 'normal',
                }}
                dangerouslySetInnerHTML={{ __html: replaceNewlinesWithBr(extractedContents[0]) }}
              />

              {/* <pre style={{ color: 'gray' }}>{extractedContents[0]}</pre> */}
            </div>
          ),
          key: '2',
        });
      }

      if (!isMessageSend && isLastOne) {
        setTimeout(() => {
          setKeyArr(['1', '2'])
        }, 0)
      }

      setThoughtListAll(Arr);
    }
  }, [item]);

  const processedText = preprocessMarkdown(isThinking() ? '' : removeThinkTags(item.text || ''));

  const handleReferenceChange = (value: boolean) => {
    console.log(value);
    console.log(item);
    setIsExpanded(value);
  };

  const [rating, setRating] = useState(0);
  const { type, id, sid } = useParams();

  const handleSurveySubmit = () => {
    if (rating > 0 && id) {
      console.log('用户提交的评分:', rating);
      appService
        .surveySubmit(id, {
          // code: '',
          content: {
            title: `AI应用满意度调研`,
            score: rating,
          },
        })
        .then(() => {
          // rating > 0 && message.success("评分更新成功")
          // setTimeout(()=>{
          //   deleteMessage(index);
          // }, 3000)
        })
        .catch((error) => {
          console.error('提交调查问卷时发生错误:', error);
        });
    }
  };

  useEffect(() => {
    handleSurveySubmit();
  }, [rating]);

  const { run, cancel, flush } = useDebounceFn(
    () => {
      if (isShow) {
        // setIsShow(false);
        setIsShow(true);

      }
    },
    {
      wait: 15,
    },
  );

  useEffect(() => {
    if (hideItem && !inViewport && !isLastOne) {
      // setIsShow(false);
      run();
    } else {
      cancel();
      // 立即刷新
      // setIsShow(true);
    }
  }, [inViewport, hideItem, isLastOne]);

  const render = () => (
    <div
      ref={ref}
      className={`mt-2 rounded-lg p-2 ${item.isUser ? 'ml-auto' : 'mr-auto'}`}
      style={{
        background: item.isUser ? '#6640FF' : '#fff',
        color: item.isUser ? '#fff' : '#474C5F',
        borderRadius: item.isUser
          ? '12px 12px 0px 12px'
          : !item.isUser && !item?.loading && item?.isSurvey
            ? '10px'
            : '0px 12px 12px 12px',
        margin: !item.isUser && !item?.loading && item?.isSurvey ? 'auto' : undefined,
        border:
          !item.isUser && !item?.loading && item?.isSurvey
            ? '2px solid rgb(167, 145, 255)'
            : undefined,
        paddingTop: !item.isUser && !item?.loading && item?.isSurvey ? '40px' : undefined,
        maxWidth: '100%',
        overflowWrap: 'break-word',
        position: 'relative',
      }}
    >
      {isShow && (
        <div>
          {!item.isUser && thoughtListAll && thoughtListAll.length > 0 && (
            <ThoughtChainALL thoughtListAll={thoughtListAll} keyArr={keyArr} setKeyArr={setKeyArr} />
          )}
          {!item?.isTextGenerate && (
            // {
            !item.isUser ?
              <ReactMarkdown
                className={`markdown ${mdStyles.markdown}`}
                // remarkPlugins={isSupported ? [remarkMath, [remarkGfm, { singleTilde: false }], remarkBreaks] : [remarkMath, remarkBreaks]}
                remarkPlugins={[remarkMath, [remarkGfm, { singleTilde: false }], remarkBreaks]}
                rehypePlugins={[rehypeKatex, rehypeRaw]}
                components={{
                  code({ node, inline, className, children, ...props }) {
                    const match = /language-(\w+)/.exec(className || '');
                    return !inline && match ? (
                      <CodeBlock language={match[1]} code={String(children).replace(/\n$/, '')} />
                    ) : (
                      <code className={className} {...props}>
                        {children}
                      </code>
                    );
                  },
                  a({ node, ...props }) {
                    const href = props.href || '';
                    const linkText = props.children[0];

                    const handleClick = (e: React.MouseEvent<HTMLAnchorElement>) => {
                      if (!href || href === '#' || href === '') {
                        e.preventDefault(); // 阻止默认跳转行为
                        e.stopPropagation(); // 阻止事件冒泡
                        handleSend(linkText as string); // 调用传入的 handleSend 函数
                      } else {
                        e.preventDefault();
                        window.open(href, '_blank');
                      }
                    };

                    return (
                      <a
                        {...props}
                        href="#"
                        onClick={handleClick}
                        style={{ cursor: 'pointer', color: '#1890ff' }}
                      >
                        {props.children}
                      </a>
                    );
                  },
                  table({ node, ...props }) {
                    return <table {...props} style={{ color: 'black' }} />;
                  },
                }}
              >
                {processedText}
              </ReactMarkdown>
              :
              <div style={{
                padding: '5px',
                whiteSpace: 'pre-wrap',    // 保留换行符和空格
                wordWrap: 'break-word',    // 兼容旧浏览器
                overflowWrap: 'break-word' // 处理长单词/URL换行
              }}>
                {item.text}
              </div>
            // }
          )}
          {item?.isTextGenerate && (
            <div style={{ padding: '5px' }}>
              {item.text}
              <SvgIcon icon="ic_rj_loading2" color="#fff" size={20} />
            </div>
          )}
          {!item?.isSurvey && (
            <div className={isExpanded ? '' : 'flex flex-wrap items-center'}>
              {!item.isUser && item.quote && item.quote.length > 0 && (
                <Reference files={item.quote} onChange={handleReferenceChange} />
              )}
              <div
                className={`ml-auto mr-1 flex items-center justify-end ${isExpanded ? 'mt-2' : ''}`}
              >
                {!item.loading && !item.isUser && index !== 0 && (
                  <CustomControl
                    isRobot={true}
                    data={item.text}
                    chatId={item.chatId}
                    dataId={item.dataId}
                    defaultLike={item?.userGoodFeedback === 'yes'}
                    defaultDislike={!!item?.userBadFeedback}
                    onDelete={deleteMessage ? () => deleteMessage(index) : undefined}
                    onRefresh={reFreshAnswer ? () => reFreshAnswer(index) : undefined}
                  />
                )}
              </div>
            </div>
          )}
          {!item.isUser && !item?.loading && !item?.isSurvey && index !== 0 && (
            <>
              {isLastOne && guessQuestions && guessQuestions.length > 0 && onQuestionClick &&
                <>
                  <GuessYouWantToAsk questions={guessQuestions} onQuestionClick={onQuestionClick} />
                </>
              }

              <div className={styles['hr-container']}>
                <div className={styles['hr-line']}></div>
              </div>
              <span
                style={{
                  color: '#8E93A4',
                  paddingLeft: '10px',
                  paddingRight: '10px',
                  fontSize: '12px',
                }}
              >
                本答案由AI生成，请谨慎参考
              </span>
            </>
          )}
        </div>
      )}
    </div>
  );

  useEffect(() => {
    // 最后一个消息大小变化后触发滚动到最后
    if (isLastOne) {
      scrollToBottom && scrollToBottom();
    }
  }, [size?.height]);

  return item.isUser ? (
    <Tooltip
      mouseLeaveDelay={0.3}
      color="#fff"
      title={
        <CustomControl
          isRobot={false}
          data={item.text}
          onDelete={deleteMessage ? () => deleteMessage(index) : undefined}
        />
      }
      placement="bottomRight"
    >
      {render()}
    </Tooltip>
  ) : (
    render()
  );
};

export default React.memo(MessageItem);
